package team.paimengshop.server_socket;

import org.json.simple.JSONObject;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailControl
{
    private static JSONObject emailAndVerCodeJsonObject = new JSONObject();

    private static final String USER = "PaiMengShop@163.com";
    private static final String PASSWORD = "HQUBDPYGEURLVNTP";

    public static void setEmailAndVerCodeJsonObject(JSONObject emailAndVerCodeJsonObject)
    {
        MailControl.emailAndVerCodeJsonObject = emailAndVerCodeJsonObject;
    }

    public static JSONObject getEmailAndVerCodeJsonObject()
    {
        return emailAndVerCodeJsonObject;
    }

    public static boolean SendEmail(String email, int verCode)
    {
        String title = "派蒙的周边商铺";
        String text = "您的注册验证码是：";
        text += verCode;
        text += "\n祝您购物愉快！";
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.163.com");  //如果发送用的是qq的就要props.put("mail.smtp.host", "smtp.qq.com");

            // 发件人的账号
            props.put("mail.user", USER);
            //发件人的密码
            props.put("mail.password", PASSWORD);

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator()
            {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(email);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject(title);

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            return true;
        }
        catch (MessagingException e)
        {
            System.out.println("发送邮件失败");
        }
        return false;
    }

    public static int CreateVerCode()
    {
        int verCode = 0;
        for(int i = 0; i < 6; i++)
        {
            verCode *= 10;
            verCode += (int)(Math.random() * 9 + 1);
        }
        return verCode;
    }

}
